package cn.sciento.mybatis.config.aspect;

import cn.sciento.mybatis.annotation.TenantDbLimitedRequest;
import cn.sciento.mybatis.helper.TenantDbLimitHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

/**

 */
@Aspect
@Component
public class TenantDbLimitAspect {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Around("@annotation(tenantDbLimitedRequest)")
    public Object tenantLimitedPointcut(ProceedingJoinPoint joinPoint, TenantDbLimitedRequest tenantDbLimitedRequest) throws Throwable {
        Object[] args = joinPoint.getArgs();
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Parameter[] parameters =  method.getParameters();
        Long tenantId = -1L;
        for(int i = 0;i<parameters.length;i++){
            if(parameters[i].getName().equals(tenantDbLimitedRequest.fieldName())){
                tenantId = (Long)args[i];
            }else {
                Annotation annotations = parameters[i].getAnnotation(PathVariable.class);
                if(annotations != null){
                    tenantId = (Long)args[i];
                }
            }
        }
        if(tenantId <0){
            throw new NullPointerException("不能获取请求租客id过滤");
        }
        TenantDbLimitHelper.setTenantId(tenantId);
        return joinPoint.proceed();
    }
}
